Page({
  data: {
    score: 0,
    gameStarted: false,
    gameOver: false,
    // 游戏参数
    gridSize: 40, // 网格大小
    snake: [], // 蛇身体
    direction: 'right', // 初始方向
    nextDirection: 'right', // 下一个方向
    food: null, // 食物位置
    gameLoop: null, // 游戏循环
    speed: 200, // 初始速度(ms)
    foodRotation: 0, // 食物旋转角度
    rainbowColors: [
      {start: '#FF5E5E', end: '#FF7D5E'},
      {start: '#FF7D5E', end: '#FFB347'},
      {start: '#FFB347', end: '#FFF275'},
      {start: '#FFF275', end: '#93FF96'},
      {start: '#93FF96', end: '#42D7F5'},
      {start: '#42D7F5', end: '#7D5FFF'},
      {start: '#7D5FFF', end: '#C774E8'},
      {start: '#C774E8', end: '#FF5E5E'}
    ],
    // 触摸控制相关
    touchStartX: 0,
    touchStartY: 0,
    touchEndX: 0,
    touchEndY: 0
  },

  onLoad() {
    // 延迟一小段时间，确保DOM已完全加载
    setTimeout(() => {
      this.initCanvas();
    }, 100);
  },

  // 初始化Canvas
  initCanvas() {
    // 使用更可靠的方式获取canvas元素
    const query = wx.createSelectorQuery()
    query.select('#gameCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        if (!res || res.length === 0 || !res[0]) {
          console.error('获取canvas元素失败，将重试...');
          // 重试获取canvas元素
          setTimeout(() => {
            this.initCanvas();
          }, 200);
          return;
        }
        
        const canvas = res[0].node;
        this.canvas = canvas;
        this.canvas.width = res[0].width;
        this.canvas.height = res[0].height;
        this.ctx = canvas.getContext('2d');
        
        // 初始化游戏但不开始
        this.prepareGame();
      })
  },

  // 准备游戏（初始化但不开始）
  prepareGame() {
    if (!this.canvas || !this.ctx) {
      console.error('Canvas未准备好，无法初始化游戏');
      return;
    }
    
    // 重置游戏状态
    this.setData({
      score: 0,
      gameOver: false,
      direction: 'right',
      nextDirection: 'right',
      speed: 200
    })
    
    // 初始化蛇
    const centerX = Math.floor(this.canvas.width / 2 / this.data.gridSize) * this.data.gridSize;
    const centerY = Math.floor(this.canvas.height / 2 / this.data.gridSize) * this.data.gridSize;
    
    this.setData({
      snake: [
        {x: centerX, y: centerY},
        {x: centerX - this.data.gridSize, y: centerY},
        {x: centerX - this.data.gridSize * 2, y: centerY}
      ]
    })
    
    // 生成食物
    this.generateFood(() => {
      // 食物生成后绘制初始界面
      this.renderGame();
    });
  },

  // 开始游戏
  startGame() {
    if (!this.canvas || !this.ctx) {
      wx.showToast({
        title: '游戏初始化失败',
        icon: 'none'
      });
      return;
    }
    
    // 如果游戏已经开始，不重复操作
    if (this.data.gameStarted && !this.data.gameOver) return;
    
    this.setData({
      gameStarted: true,
      gameOver: false
    });
    
    // 开始游戏循环
    this.startGameLoop();
  },

  // 开始游戏循环
  startGameLoop() {
    // 清除之前的循环
    if (this.data.gameLoop) {
      clearInterval(this.data.gameLoop);
    }
    
    // 创建新的游戏循环
    const loop = setInterval(() => {
      this.updateGame();
      this.renderGame();
    }, this.data.speed);
    
    this.setData({
      gameLoop: loop
    });
  },

  // 更新游戏状态
  updateGame() {
    if (this.data.gameOver || !this.data.gameStarted) return;
    
    // 检查食物是否存在
    if (!this.data.food) {
      this.generateFood();
      return;
    }
    
    // 更新方向
    this.setData({
      direction: this.data.nextDirection
    });
    
    // 计算新的蛇头位置
    const head = {...this.data.snake[0]};
    switch (this.data.direction) {
      case 'up':
        head.y -= this.data.gridSize;
        break;
      case 'down':
        head.y += this.data.gridSize;
        break;
      case 'left':
        head.x -= this.data.gridSize;
        break;
      case 'right':
        head.x += this.data.gridSize;
        break;
    }
    
    // 检查是否撞墙
    if (
      head.x < 0 || 
      head.x >= this.canvas.width || 
      head.y < 0 || 
      head.y >= this.canvas.height
    ) {
      this.gameOver();
      return;
    }
    
    // 检查是否撞到自己
    for (let i = 0; i < this.data.snake.length; i++) {
      if (this.data.snake[i].x === head.x && this.data.snake[i].y === head.y) {
        this.gameOver();
        return;
      }
    }
    
    // 将新头部添加到蛇身体
    const newSnake = [head, ...this.data.snake];
    
    // 检查是否吃到食物
    if (head.x === this.data.food.x && head.y === this.data.food.y) {
      // 加分
      this.setData({
        score: this.data.score + 10
      });
      
      // 生成新食物
      this.generateFood();
      
      // 增加速度 (最小100ms)
      const newSpeed = Math.max(100, this.data.speed - 5);
      this.setData({
        speed: newSpeed
      });
      
      // 重新开始游戏循环以应用新速度
      this.startGameLoop();
      
      // 检查是否胜利（蛇占满屏幕）
      const totalCells = (this.canvas.width / this.data.gridSize) * (this.canvas.height / this.data.gridSize);
      if (newSnake.length >= totalCells) {
        this.setData({
          score: this.data.score + 100 // 胜利加分
        });
        wx.showToast({
          title: '恭喜你胜利了！',
          icon: 'none'
        });
        this.gameOver();
        return;
      }
    } else {
      // 没吃到食物，移除尾部
      newSnake.pop();
    }
    
    // 更新蛇
    this.setData({
      snake: newSnake,
      foodRotation: (this.data.foodRotation + 2) % 360
    });
  },

  // 渲染游戏
  renderGame() {
    if (!this.canvas || !this.ctx) return;
    
    // 清除画布
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    
    // 绘制网格背景
    this.drawGrid();
    
    // 绘制蛇
    this.data.snake.forEach((segment, index) => {
      // 根据位置获取彩虹色
      const colorIndex = index % this.data.rainbowColors.length;
      const gradient = this.ctx.createLinearGradient(
        segment.x, 
        segment.y, 
        segment.x + this.data.gridSize, 
        segment.y + this.data.gridSize
      );
      gradient.addColorStop(0, this.data.rainbowColors[colorIndex].start);
      gradient.addColorStop(1, this.data.rainbowColors[colorIndex].end);
      
      // 绘制圆角矩形
      const radius = 8;
      const x = segment.x;
      const y = segment.y;
      const width = this.data.gridSize;
      const height = this.data.gridSize;
      
      this.ctx.beginPath();
      this.ctx.moveTo(x + radius, y);
      this.ctx.arcTo(x + width, y, x + width, y + height, radius);
      this.ctx.arcTo(x + width, y + height, x, y + height, radius);
      this.ctx.arcTo(x, y + height, x, y, radius);
      this.ctx.arcTo(x, y, x + width, y, radius);
      this.ctx.closePath();
      
      this.ctx.fillStyle = gradient;
      this.ctx.fill();
      
      // 绘制蛇眼 (仅头部)
      if (index === 0) {
        this.ctx.fillStyle = 'white';
        const eyeSize = 5;
        const eyeOffset = 8;
        
        switch (this.data.direction) {
          case 'up':
            this.ctx.beginPath();
            this.ctx.arc(x + eyeOffset, y + eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.arc(x + width - eyeOffset, y + eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.fill();
            break;
          case 'down':
            this.ctx.beginPath();
            this.ctx.arc(x + eyeOffset, y + height - eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.arc(x + width - eyeOffset, y + height - eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.fill();
            break;
          case 'left':
            this.ctx.beginPath();
            this.ctx.arc(x + eyeOffset, y + eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.arc(x + eyeOffset, y + height - eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.fill();
            break;
          case 'right':
            this.ctx.beginPath();
            this.ctx.arc(x + width - eyeOffset, y + eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.arc(x + width - eyeOffset, y + height - eyeOffset, eyeSize, 0, Math.PI * 2);
            this.ctx.fill();
            break;
        }
      }
    });
    
    // 绘制食物 (旋转的星星)
    if (this.data.food) {
      this.ctx.save();
      this.ctx.translate(
        this.data.food.x + this.data.gridSize / 2, 
        this.data.food.y + this.data.gridSize / 2
      );
      this.ctx.rotate(this.data.foodRotation * Math.PI / 180);
      
      // 绘制五角星
      this.drawStar(0, 0, 5, this.data.gridSize / 4, this.data.gridSize / 2);
      
      this.ctx.restore();
    }
  },

  // 绘制网格背景
  drawGrid() {
    if (!this.canvas || !this.ctx) return;
    
    this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.05)';
    this.ctx.lineWidth = 1;
    
    // 绘制水平线
    for (let y = 0; y <= this.canvas.height; y += this.data.gridSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(0, y);
      this.ctx.lineTo(this.canvas.width, y);
      this.ctx.stroke();
    }
    
    // 绘制垂直线
    for (let x = 0; x <= this.canvas.width; x += this.data.gridSize) {
      this.ctx.beginPath();
      this.ctx.moveTo(x, 0);
      this.ctx.lineTo(x, this.canvas.height);
      this.ctx.stroke();
    }
  },

  // 绘制星星
  drawStar(cx, cy, spikes, innerRadius, outerRadius) {
    if (!this.ctx) return;
    
    let rot = Math.PI / 2 * 3;
    let x = cx;
    let y = cy;
    let step = Math.PI / spikes;
    
    this.ctx.beginPath();
    this.ctx.moveTo(cx, cy - outerRadius);
    
    for (let i = 0; i < spikes; i++) {
      x = cx + Math.cos(rot) * outerRadius;
      y = cy + Math.sin(rot) * outerRadius;
      this.ctx.lineTo(x, y);
      rot += step;
      
      x = cx + Math.cos(rot) * innerRadius;
      y = cy + Math.sin(rot) * innerRadius;
      this.ctx.lineTo(x, y);
      rot += step;
    }
    
    this.ctx.lineTo(cx, cy - outerRadius);
    this.ctx.closePath();
    
    // 创建渐变颜色
    const gradient = this.ctx.createLinearGradient(
      cx - outerRadius, 
      cy - outerRadius, 
      cx + outerRadius, 
      cy + outerRadius
    );
    gradient.addColorStop(0, '#FFD700');
    gradient.addColorStop(1, '#FFA500');
    
    this.ctx.fillStyle = gradient;
    this.ctx.fill();
  },

  // 生成食物
  generateFood(callback) {
    if (!this.canvas) {
      if (callback) callback();
      return;
    }
    
    // 计算可能的位置
    const maxX = Math.floor(this.canvas.width / this.data.gridSize) - 1;
    const maxY = Math.floor(this.canvas.height / this.data.gridSize) - 1;
    
    // 检查是否还有空间生成食物
    const totalCells = (maxX + 1) * (maxY + 1);
    if (this.data.snake.length >= totalCells) {
      // 没有空间了，游戏胜利
      if (callback) callback();
      return;
    }
    
    let newFood;
    let attempts = 0;
    const maxAttempts = 100; // 限制最大尝试次数
    
    // 确保食物不会出现在蛇身上
    do {
      attempts++;
      const x = Math.floor(Math.random() * maxX) * this.data.gridSize;
      const y = Math.floor(Math.random() * maxY) * this.data.gridSize;
      newFood = {x, y};
      
      // 如果尝试次数过多，强制退出循环
      if (attempts >= maxAttempts) {
        console.warn('生成食物尝试次数过多，可能没有足够空间');
        break;
      }
    } while (
      this.data.snake.some(segment => segment.x === newFood.x && segment.y === newFood.y)
    );
    
    this.setData({
      food: newFood
    }, () => {
      if (callback) callback();
    });
  },

  // 处理键盘事件
  handleKeyDown(e) {
    if (!this.data.gameStarted || this.data.gameOver) return;
    
    // 阻止相反方向
    const currentDirection = this.data.direction;
    
    switch(e.keyCode) {
      case 38: // 上
        if (currentDirection !== 'down') {
          this.setData({nextDirection: 'up'});
        }
        break;
      case 40: // 下
        if (currentDirection !== 'up') {
          this.setData({nextDirection: 'down'});
        }
        break;
      case 37: // 左
        if (currentDirection !== 'right') {
          this.setData({nextDirection: 'left'});
        }
        break;
      case 39: // 右
        if (currentDirection !== 'left') {
          this.setData({nextDirection: 'right'});
        }
        break;
    }
  },

  // 触摸开始
  handleTouchStart(e) {
    if (!this.data.gameStarted || this.data.gameOver) return;
    
    this.setData({
      touchStartX: e.touches[0].clientX,
      touchStartY: e.touches[0].clientY
    });
  },

  // 触摸移动
  handleTouchMove(e) {
    if (!this.data.gameStarted || this.data.gameOver) return;
    
    this.setData({
      touchEndX: e.touches[0].clientX,
      touchEndY: e.touches[0].clientY
    });
  },

  // 触摸结束 (处理滑动方向)
  handleTouchEnd() {
    if (!this.data.gameStarted || this.data.gameOver) return;
    
    const dx = this.data.touchEndX - this.data.touchStartX;
    const dy = this.data.touchEndY - this.data.touchStartY;
    
    // 确定滑动方向 (水平或垂直)
    if (Math.abs(dx) > Math.abs(dy)) {
      // 水平滑动
      if (dx > 0 && this.data.direction !== 'left') {
        this.setData({nextDirection: 'right'});
      } else if (dx < 0 && this.data.direction !== 'right') {
        this.setData({nextDirection: 'left'});
      }
    } else {
      // 垂直滑动
      if (dy > 0 && this.data.direction !== 'up') {
        this.setData({nextDirection: 'down'});
      } else if (dy < 0 && this.data.direction !== 'down') {
        this.setData({nextDirection: 'up'});
      }
    }
  },

  // 游戏结束
  gameOver() {
    clearInterval(this.data.gameLoop);
    this.setData({
      gameOver: true,
      gameStarted: false
    });
  },

  // 重新开始游戏
  restartGame() {
    clearInterval(this.data.gameLoop);
    this.prepareGame();
  },

  onUnload() {
    // 清除游戏循环和事件监听
    clearInterval(this.data.gameLoop);
    wx.offKeyDown();
  }
})
    